/*
 * MIT License
 *
 * Copyright (c) 2024-2048 冰羽
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package cn.star.framework.excel.read;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ReflectUtil;
import cn.star.framework.excel.convert.CellValueConverter;
import cn.star.framework.excel.convert.CellValueValidateRule;
import cn.star.framework.excel.convert.ColumnAutoMount;
import cn.star.framework.excel.core.Column;
import cn.star.framework.excel.core.RowWrapper;
import cn.star.framework.excel.enhance.GlobalConverterRegister;
import cn.star.framework.excel.read.status.SheetStatus;
import com.alibaba.excel.context.AnalysisContext;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;

/**
 * 读取行数据的回调函数抽象实现<br>
 *
 * @author zhaoweiping
 *     <p style='color: red'>Created on 2024-09-23 11:06:00
 * @since 3.0.0
 */
@Slf4j
public abstract class SimpleReadRowCallback implements ReadRowCallback {

  @Override
  public void callback(
      List<RowWrapper> data, ReadContext readContext, AnalysisContext context, Exception e) {
    String name = context.readSheetHolder().getSheetName();
    SheetStatus sheetStatus =
        readContext.getSheetStatuses().stream()
            .filter(i -> name.equals(i.getName()))
            .findFirst()
            .orElse(null);
    // 如果从上下文中不能成功获取读取当前Sheet状态时是一个位置的错误，抛出异常
    Assert.isFalse(
        sheetStatus == null,
        "According to the name: {}, the corresponding Sheet page status was not obtained, and the operation was terminated",
        name);
    if (data == null) {
      // 此处不能抛出异常，因为一批数据为空不代表错误
      log.error("The current dataset is empty, and the operation has been terminated");
      return;
    }
    // 处理数据
    data.forEach(wrapper -> this.invoke(sheetStatus, wrapper));
  }

  /**
   * 处理每一行数据并记录处理结果到{@param sheetStatus}中
   *
   * @param sheetStatus
   * @param wrapper
   */
  protected abstract void invoke(SheetStatus sheetStatus, RowWrapper wrapper);

  /**
   * 设置行实例的列数据
   *
   * @param instance 处于正在转船处理{@link #invoke(SheetStatus, RowWrapper)}中的一行数据
   * @param data 已经读取成功的原始行数据
   * @param column 列信息
   * @throws Exception
   */
  protected void setRowInstanceColumValue(Object instance, Column column, RowWrapper wrapper)
      throws Exception {
    Map<String, Object> data = wrapper.getData();
    String name = column.getKey();
    Object value = this.valueConvert(column, data.get(name), wrapper);
    this.valueValidate(column, value);

    ReflectUtil.setFieldValue(instance, name, value);
  }

  /**
   * 字段值转换
   *
   * @param column
   * @param value
   * @return
   */
  @SuppressWarnings({"unchecked", "rawtypes"})
  protected Object valueConvert(Column column, Object value, RowWrapper wrapper) {
    CellValueConverter converter = column.getConverter();
    if (converter != null) {
      return converter.convert(column, value, wrapper);
    }
    List<CellValueConverter> converters = GlobalConverterRegister.getCellValueConverters();
    for (CellValueConverter c : converters) {
      if (c instanceof ColumnAutoMount && ((ColumnAutoMount) c).isSupportType(column.getType())) {
        value = c.convert(column, value, wrapper);
      }
    }

    return value;
  }

  /**
   * 字段值校验
   *
   * @param column {@link Column}
   * @param value 值
   */
  protected void valueValidate(Column column, Object value) throws Exception {
    List<CellValueValidateRule> cellValueValidateRules = column.getCellValueValidateRules();
    for (CellValueValidateRule cellValueValidateRule : cellValueValidateRules) {
      cellValueValidateRule.validate(column, value);
    }
  }
}
